'use client'

import { useEffect, useState } from 'react'
import { PartOfSpeech } from '@/types'
import ImportExportToolbar from './ImportExportToolbar'
import { downloadCsv, downloadXls, downloadXlsx, parseCsv, parseExcelXml, parseXlsx } from '@/lib/importExportUtils'

interface PosForm {
  key: string
  name: string
  englishName: string
  description: string
}

const emptyForm: PosForm = { key: '', name: '', englishName: '', description: '' }

const normalizeHeaderKey = (raw: string) => {
  const trimmed = (raw || '').trim()
  const lower = trimmed.toLowerCase()
  const map: Record<string, string> = {
    key: 'key', 简码: 'key',
    name: 'name', '中文名称': 'name',
    englishname: 'englishname', '英文全称': 'englishname',
    description: 'description', '说明': 'description',
  }
  return map[trimmed] ?? map[lower] ?? lower
}

const extractImportPayloads = (rows: string[][]) => {
  if (rows.length === 0) {
    return { error: '文件为空', payloads: [] as { rowIndex: number; body: any }[], failed: 0, errors: [] as string[] }
  }
  const [headerRow, ...data] = rows
  const header = headerRow.map(h => normalizeHeaderKey(String(h)))
  const idxKey = header.indexOf('key')
  const idxName = header.indexOf('name')
  const idxEnglish = header.indexOf('englishname')
  const idxDesc = header.indexOf('description')
  if (idxKey < 0) {
    return { error: '缺少必要列：key', payloads: [], failed: 0, errors: [] as string[] }
  }
  const payloads: { rowIndex: number; body: any }[] = []
  const errors: string[] = []
  let failed = 0
  for (let i = 0; i < data.length; i++) {
    const row = data[i]
    const key = String(row[idxKey] || '').trim()
    if (!key) {
      failed++
      errors.push(`第${i + 2}行：key 不能为空`)
      continue
    }
    payloads.push({
      rowIndex: i,
      body: {
        key,
        name: idxName >= 0 ? String(row[idxName] || '').trim() : undefined,
        englishName: idxEnglish >= 0 ? String(row[idxEnglish] || '').trim() : undefined,
        description: idxDesc >= 0 ? String(row[idxDesc] || '').trim() : undefined,
      },
    })
  }
  return { error: null, payloads, failed, errors }
}

export default function PartOfSpeechManager() {
	const [items, setItems] = useState<PartOfSpeech[]>([])
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
	const [showModal, setShowModal] = useState(false)
	const [editing, setEditing] = useState<PartOfSpeech | null>(null)
  const [form, setForm] = useState<PosForm>(emptyForm)
  const [showDetailModal, setShowDetailModal] = useState(false)
  const [detailItem, setDetailItem] = useState<PartOfSpeech | null>(null)
  const [showDeleteMenu, setShowDeleteMenu] = useState(false)
  const [isImporting, setIsImporting] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize] = useState(20)

	useEffect(() => { fetchList() }, [])

  useEffect(() => {
    setSelectedIds(prev => {
      const ids = new Set<string>()
      items.forEach(it => { if (prev.has(it.id)) ids.add(it.id) })
      return ids
    })
  }, [items])

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (!target.closest('[data-menu-container]')) {
        setShowDeleteMenu(false)
      }
    }
    if (showDeleteMenu) {
      document.addEventListener('click', handleClickOutside)
      return () => document.removeEventListener('click', handleClickOutside)
    }
  }, [showDeleteMenu])

	const fetchList = async () => {
		try {
			const res = await fetch('/api/pos')
			const data = await res.json()
			if (data.success) setItems(data.items)
		} catch {}
	}

  const openCreate = () => {
    setEditing(null)
    setForm(emptyForm)
    setShowModal(true)
  }

  const openEdit = (item: PartOfSpeech) => {
    setEditing(item)
    setForm({
      key: item.key,
      name: item.name,
      englishName: item.englishName || '',
      description: item.description || ''
    })
    setShowModal(true)
  }

  const openDetail = (item: PartOfSpeech) => {
    setDetailItem(item)
    setShowDetailModal(true)
  }

	const submit = async (e: React.FormEvent) => {
		e.preventDefault()
    const payload = {
      key: form.key.trim(),
      name: form.name.trim(),
      englishName: form.englishName.trim() || undefined,
      description: form.description.trim() || undefined
    }
    if (!payload.key || !payload.name) {
      alert('Key 和 名称不能为空')
      return
    }
		try {
			if (editing) {
        const res = await fetch(`/api/pos/${editing.id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
				const data = await res.json()
				if (!data.success) return alert(data.message || '更新失败')
			} else {
        const res = await fetch('/api/pos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
				const data = await res.json()
				if (!data.success) return alert(data.message || '创建失败')
			}
			setShowModal(false)
			fetchList()
		} catch { alert('操作失败') }
	}

	const del = async (id: string) => {
		if (!confirm('确认删除该词性吗？')) return
		try {
			const res = await fetch(`/api/pos/${id}`, { method: 'DELETE' })
			const data = await res.json()
			if (!data.success) return alert(data.message || '删除失败')
			fetchList()
		} catch { alert('删除失败') }
  }

  const deleteSelected = async () => {
    if (selectedIds.size === 0) return
    if (!confirm(`确认删除选中的 ${selectedIds.size} 个词性吗？`)) return
    try {
    for (const id of Array.from(selectedIds)) {
        const res = await fetch(`/api/pos/${id}`, { method: 'DELETE' })
        const data = await res.json()
        if (!data.success) throw new Error(data.message)
      }
      setSelectedIds(new Set())
      fetchList()
    } catch (e) {
      alert('删除失败')
    }
  }

  const deleteAll = async () => {
    if (items.length === 0) return
    if (!confirm(`确认删除全部 ${items.length} 个词性吗？`)) return
    if (!confirm('再次确认：该操作不可恢复，确定要删除全部词性吗？')) return
    try {
      for (const it of items) {
        await fetch(`/api/pos/${it.id}`, { method: 'DELETE' })
      }
      setSelectedIds(new Set())
      fetchList()
    } catch {
      alert('删除失败')
    }
  }

  const paginatedItems = items.slice((currentPage - 1) * pageSize, currentPage * pageSize)
  const totalPages = Math.ceil(items.length / pageSize)

  const toggleSelectAll = (checked: boolean) => {
    if (checked) {
      const pageIds = new Set(paginatedItems.map(it => it.id))
      setSelectedIds(prev => {
        const next = new Set(prev)
        pageIds.forEach(id => next.add(id))
        return next
      })
    } else {
      const pageIds = new Set(paginatedItems.map(it => it.id))
      setSelectedIds(prev => {
        const next = new Set(prev)
        pageIds.forEach(id => next.delete(id))
        return next
      })
    }
  }

  const toggleSelectOne = (id: string, checked: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      if (checked) next.add(id); else next.delete(id)
      return next
    })
  }

  useEffect(() => {
    // 当数据变化时，重置到第一页
    setCurrentPage(1)
  }, [items])

  const handleExportSelected = (format: 'csv' | 'xls' | 'xlsx') => {
    if (selectedIds.size === 0) return
    const selected = items.filter(it => selectedIds.has(it.id))
    if (selected.length === 0) return
    const headers = ['简码', '中文名称', '英文全称', '说明']
    const rows = selected.map(it => [it.key, it.name, it.englishName || '', it.description || ''])
    const filename = `pos_selected_${Date.now()}`
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows)
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows)
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows)
    }
  }

  const handleExportAll = (format: 'csv' | 'xls' | 'xlsx') => {
    if (items.length === 0) return
    const headers = ['简码', '中文名称', '英文全称', '说明']
    const rows = items.map(it => [it.key, it.name, it.englishName || '', it.description || ''])
    const filename = `pos_all_${Date.now()}`
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows)
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows)
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows)
    }
  }

  const handleDownloadTemplate = (format: 'csv' | 'xls' | 'xlsx') => {
    const headers = ['简码', '中文名称', '英文全称', '说明']
    const example = ['n', '名词', 'noun', '表示人或事物']
    if (format === 'csv') {
      downloadCsv('pos_template.csv', headers, [example])
    } else if (format === 'xls') {
      downloadXls('pos_template.xls', headers, [example])
    } else {
      downloadXlsx('pos_template.xlsx', headers, [example])
    }
  }

const importRows = async (rows: string[][]) => {
  const { error, payloads, failed: initialFailed, errors: preErrors } = extractImportPayloads(rows)
  if (error) {
    alert(error)
    return
  }
  let ok = 0
  let failed = initialFailed
  const errors = [...preErrors]
  for (const { body, rowIndex } of payloads) {
    try {
      const res = await fetch('/api/pos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      const json = await res.json()
      if (json.success) ok++
      else {
        failed++
        errors.push(`第${rowIndex + 2}行：${json.message || '创建失败'}`)
      }
    } catch {
      failed++
      errors.push(`第${rowIndex + 2}行：网络错误`)
    }
  }
  await fetchList()
  alert(`导入完成：成功 ${ok} 条，失败 ${failed} 条${errors.length ? '\n\n前5个错误：\n' + errors.slice(0, 5).join('\n') : ''}`)
}

  const handleImport = async (file: File, format: 'csv' | 'xls' | 'xlsx') => {
    setIsImporting(true)
    try {
      let rows: string[][]
      if (format === 'csv') {
        const text = await file.text()
        rows = parseCsv(text)
      } else if (format === 'xls') {
        const text = await file.text()
        rows = parseExcelXml(text)
      } else {
        rows = await parseXlsx(file)
      }
      await importRows(rows)
    } catch (e) {
      if (e instanceof Error && e.message.includes('xlsx')) {
        alert('请先安装 xlsx 库: npm install xlsx')
      } else {
        alert('导入失败')
      }
    } finally {
      setIsImporting(false)
    }
  }

	return (
		<div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px', flexWrap: 'wrap', gap: '10px' }}>
				<h2>词性管理</h2>
        <div style={{ display: 'flex', gap: '10px' }}>
				<button className="btn btn-primary" onClick={openCreate}>添加词性</button>
			</div>
      </div>

			<div className="card">
        <div style={{ display: 'flex', gap: '10px', marginBottom: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', display: 'inline-block' }} data-menu-container>
            <button className="btn btn-secondary" onClick={(e) => { e.stopPropagation(); setShowDeleteMenu(!showDeleteMenu); }}>
              删除 {showDeleteMenu ? '▼' : '▶'}
            </button>
            {showDeleteMenu && (
              <div style={{ position: 'absolute', top: '100%', left: 0, backgroundColor: 'white', border: '1px solid #ddd', borderRadius: '4px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)', zIndex: 1000, minWidth: '150px', marginTop: '4px' }}>
                <button className="btn" style={{ width: '100%', textAlign: 'left', padding: '8px', border: 'none', background: 'none', cursor: 'pointer', color: '#333', borderBottom: '1px solid #eee' }} onClick={() => { deleteSelected(); setShowDeleteMenu(false); }} disabled={selectedIds.size === 0}>
                  删除选中 ({selectedIds.size})
                </button>
                <button className="btn" style={{ width: '100%', textAlign: 'left', padding: '8px', border: 'none', background: 'none', cursor: 'pointer', color: '#dc3545', fontWeight: 'bold' }} onClick={() => { deleteAll(); setShowDeleteMenu(false); }} disabled={items.length === 0}>
                  删除全部 ({items.length})
                </button>
              </div>
            )}
          </div>

          <ImportExportToolbar
            onExportSelected={handleExportSelected}
            onExportAll={handleExportAll}
            onImport={handleImport}
            onDownloadTemplate={handleDownloadTemplate}
            isImporting={isImporting}
            selectedCount={selectedIds.size}
            totalCount={items.length}
          />
        </div>

        <div style={{ overflowX: 'auto' }}>
				<table style={{ width: '100%', borderCollapse: 'collapse' }}>
					<thead>
						<tr style={{ backgroundColor: '#f5f5f5' }}>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>
                  <input type="checkbox" checked={paginatedItems.length > 0 && paginatedItems.every(it => selectedIds.has(it.id))} onChange={e => toggleSelectAll(e.target.checked)} />
                </th>
							<th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>Key</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>中文名称</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>英文全称</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>说明</th>
							<th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>操作</th>
						</tr>
					</thead>
					<tbody>
						{paginatedItems.map(it => (
							<tr key={it.id} style={{ borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '10px' }}>
                    <input type="checkbox" checked={selectedIds.has(it.id)} onChange={e => toggleSelectOne(it.id, e.target.checked)} />
                  </td>
								<td style={{ padding: '10px' }}>{it.key}</td>
								<td style={{ padding: '10px' }}>{it.name}</td>
                  <td style={{ padding: '10px' }}>{it.englishName || '-'}</td>
                  <td style={{ padding: '10px', maxWidth: '260px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.description || '-'}</td>
								<td style={{ padding: '10px' }}>
                    <button className="btn" style={{ marginRight: 8 }} onClick={() => openDetail(it)}>详情</button>
									<button className="btn btn-secondary" style={{ marginRight: 8 }} onClick={() => openEdit(it)}>编辑</button>
									<button className="btn btn-danger" onClick={() => del(it.id)}>删除</button>
								</td>
							</tr>
						))}
						{items.length === 0 && (
                <tr><td colSpan={6} style={{ padding: '16px', textAlign: 'center' }}>暂无词性</td></tr>
						)}
					</tbody>
				</table>
        </div>
        {items.length > 0 && (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '15px', borderTop: '1px solid #eee' }}>
            <div>
              共 {items.length} 条，第 {currentPage} / {totalPages} 页
            </div>
            <div style={{ display: 'flex', gap: '8px' }}>
              <button className="btn" onClick={() => setCurrentPage(1)} disabled={currentPage === 1}>首页</button>
              <button className="btn" onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1}>上一页</button>
              <button className="btn" onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages}>下一页</button>
              <button className="btn" onClick={() => setCurrentPage(totalPages)} disabled={currentPage === totalPages}>末页</button>
            </div>
          </div>
        )}
			</div>

			{showModal && (
				<div className="modal" onClick={() => setShowModal(false)}>
					<div className="modal-content" onClick={(e) => e.stopPropagation()}>
						<h2>{editing ? '编辑词性' : '添加词性'}</h2>
						<form onSubmit={submit}>
							<div style={{ marginBottom: '12px' }}>
								<label style={{ display: 'block', marginBottom: 6, fontWeight: 'bold' }}>Key</label>
                <input className="input" value={form.key} onChange={e => setForm({ ...form, key: e.target.value })} required />
							</div>
							<div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 'bold' }}>中文名称</label>
								<input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required />
							</div>
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 'bold' }}>英文全称</label>
                <input className="input" value={form.englishName} onChange={e => setForm({ ...form, englishName: e.target.value })} placeholder="例如：noun" />
              </div>
              <div style={{ marginBottom: '12px' }}>
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 'bold' }}>说明</label>
                <textarea className="input" value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} rows={4} placeholder="词性的补充说明" />
              </div>
							<div style={{ display: 'flex', gap: 10 }}>
								<button type="submit" className="btn btn-primary">保存</button>
								<button type="button" className="btn btn-secondary" onClick={() => setShowModal(false)}>取消</button>
							</div>
						</form>
					</div>
				</div>
			)}

      {showDetailModal && detailItem && (
        <div className="modal" onClick={() => { setShowDetailModal(false); setDetailItem(null) }}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: '420px' }}>
            <h2>词性详情</h2>
            <div style={{ marginBottom: '10px' }}><strong>ID:</strong> {detailItem.id}</div>
            <div style={{ marginBottom: '10px' }}><strong>Key:</strong> {detailItem.key}</div>
            <div style={{ marginBottom: '10px' }}><strong>中文名称:</strong> {detailItem.name}</div>
            <div style={{ marginBottom: '10px' }}><strong>英文全称:</strong> {detailItem.englishName || '-'}</div>
            <div style={{ marginBottom: '10px' }}><strong>说明:</strong> {detailItem.description || '-'}</div>
            <div style={{ display: 'flex', gap: '10px' }}>
              <button className="btn btn-secondary" onClick={() => { setShowDetailModal(false); setDetailItem(null) }}>关闭</button>
              <button className="btn btn-primary" onClick={() => { setShowDetailModal(false); if (detailItem) openEdit(detailItem) }}>编辑</button>
            </div>
          </div>
        </div>
      )}

      {isImporting && (
        <div className="modal" style={{ cursor: 'wait' }}>
          <div className="modal-content" style={{ pointerEvents: 'none' }}>正在导入，请稍候...</div>
        </div>
      )}
		</div>
	)
}
